<?php
/**
 * Created by PhpStorm.
 * User: VJLau
 * Date: 2018/1/30
 * Time: 下午3:12
 */
defined('IN_IA') or exit('Access Denied');

define("BONTRIP", "vj_bontrip");
define('ZC_ROOT', IA_ROOT . '/addons/vj_bontrip');
define("WEB_RES", "/addons/" . BONTRIP . "/template/");
define("MOBILE_RES", "/addons/" . BONTRIP . "/template/mobile/");

class VJ_bontripModuleSite extends WeModuleSite
{
    public function __construct()
    {
        global $_W;

        // 配置 $this->module['config'];
        // WeUtility::logging('info', $config);
    }

    private function __web($f_name)
    {
        global $_W, $_GPC;
        $uniacid = $_W['uniacid'];

        include_once 'inc/web/' . strtolower(substr($f_name, 5)) . '.inc.php';
    }

    private function __mobile($f_name)
    {
        global $_W, $_GPC;
        $uniacid = $_W['uniacid'];
        // 加载用户信息
        $userinfo = $_W['fans'];
        $userinfo = $userinfo['tag'];
        if ((empty($userinfo['avatar'])) || strtolower(substr($f_name, 8)) == "list") {
            load()->model('mc');
            $userinfo = mc_oauth_userinfo();
        }
        if (empty($_SESSION['vj_member'])) {
            $openid = $userinfo['openid'];
            // 尝试用openid登陆
            if (!empty($openid) && $openid != -1) {
                $member = pdo_fetch("SELECT * FROM " . tablename('bontrip_member')
                    . " WHERE openid = '{$openid}' AND uniacid={$uniacid} AND deleted_at is null");
                if (!empty($member)) {
                    //昵称头像实时更新
                    if ($userinfo['avatar'] !== $member['avatar'] || stripslashes($userinfo['nickname']) !== $member['nick_name']) {
                        $member['avatar'] = $userinfo['avatar'];
                        $member['nick_name'] = stripslashes($userinfo['nickname']);
                        pdo_update('bontrip_member', array('avatar' => $member['avatar'],'nick_name' => $member['nick_name']), array('id' => $member['id']));
                    }
                    $_SESSION['vj_member'] = base64_encode(iserializer($member));
                }
            }
        }

        // 登录验证
        if (!in_array($_GPC['do'], array('register'))) {
            if (empty($_SESSION['vj_member'])) {
                header("location: " . $this->createMobileUrl('register'));
                exit;
            }
        }

        // 系统
        $config = $this->module['config'];
        $share = array(
            'share_link' => $_W['siteroot'] . 'app/' . substr(murl('entry//list', array('m' => 'vj_bontrip'), true), 2),
            'share_title' => empty($config['share_title']) ? '知行' : $config['share_title'],
            'share_description' => empty($config['share_description']) ? '知行' : $config['share_description'],
            'share_img' => empty($config['share_img']) ? '' : tomedia($config['share_img']),
        );
        include_once 'inc/mobile/' . strtolower(substr($f_name, 8)) . '.inc.php';
    }

    private function __json($ret = 0, $msg = '', $extend = array())
    {
        return json_encode(array_merge(array('ret' => $ret, 'msg' => $msg), $extend));
    }

    //////////////////////////////////////////////////////////////////////
    // 后台功能 ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////

    public function doWebRegion()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebDest()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebSingle()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebSingleorder()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebMember()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebSku()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebOneday()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebOnedayorder()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebQuality()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebQualityorder()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebArticle()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebLine()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebHotel()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebCurrency()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebInsurance()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebInsuranceprice()
    {
        $this->__web(__FUNCTION__);
    }

    public function doWebInsuranceorder()
    {
        $this->__web(__FUNCTION__);
    }

    //////////////////////////////////////////////////////////////////////
    // 前端功能 ///////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////

    public function doMobileList()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileDestination()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileSingle()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileOneday()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileQuality()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileDest()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileRegister()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileGoods()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobilePayment()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileLine()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileInsurance()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileinsured()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileMe()
    {
        $this->__mobile(__FUNCTION__);
    }

    public function doMobileOrder()
    {
        $this->__mobile(__FUNCTION__);
    }

    //所有ajax方法
    public function doMobileAjax()
    {
        $this->__mobile(__FUNCTION__);
    }

    /**
     * 发送短信
     */
    public function doMobileSms()
    {
        global $_W, $_GPC;
        $mobile = $_POST['mobile'];
        $code_type = intval($_POST['code_type']); // 1:注册,2:忘记密码

        if (empty($mobile)) {
            return $this->__json(500, '手机不能为空');
        }

        $ip = $_W['clientip'];
        $uniacid = $_W['uniacid'];

        /*
         * 根据IP频率验证,一分种能只能获取两条短信
         */
        $sms_last = pdo_fetchall("SELECT * FROM " . tablename('bontrip_auth_code')
            . " WHERE access_ip = '{$ip}' AND created_at > " . (TIMESTAMP - 60) . " ORDER BY created_at DESC");
        if (count($sms_last) >= 2) {
            return $this->__json(500, '短信发送太频繁');
        }

        /*
         * 代码类型验证
         */
        switch ($code_type) {
            case 1:
                $member = pdo_fetch("SELECT * FROM " . tablename('bontrip_member')
                    . " WHERE mobile = {$mobile} AND uniacid={$uniacid} AND deleted_at is null");
                if (!empty($member)) {
                    return $this->__json(500, '手机已注册');
                }
                break;
            case 2:
                $member = pdo_fetch("SELECT * FROM " . tablename('bontrip_member')
                    . " WHERE mobile = {$mobile} AND uniacid={$uniacid} AND deleted_at is null");
                if (empty($member)) {
                    return $this->__json(500, '不存在此手机');
                }
                break;
            default:
                return $this->__json(500, '参数错误');
        }

        /*
         * TODO 发送短信
         */
        $setting = pdo_fetch("SELECT settings FROM " . tablename('uni_account_modules') . " WHERE module = :module AND uniacid = :uniacid", array(':module' => 'vj_bontrip', ':uniacid' => $_W['uniacid']));
        $setting = iunserializer($setting['settings']);

        if ($setting["isproduction"] == 1) {
            $verify_code = rand(1000, 9999);
            $send_time = date('Y-m-d H:i', time());
            if (empty($setting["duanxinbao_content"])) {
                $content = "【知行】您的验证码为{$verify_code}，于{$send_time}提交，1分钟内有效";
            } else {
                $c = str_replace('{$verify_code}', $verify_code, $setting["duanxinbao_content"]);
                $content = str_replace('{$send_time}', $send_time, $c);
            }

            $res = $this->send($mobile, $content);
            if (!$res) {
                return $this->__json(500, '短信发送失败，请联系客服。');

            }
        } else {
            $verify_code = '336699';
        }

        $data = array(
            'mobile' => $mobile,
            'auth_code' => $verify_code,
            'access_ip' => $ip,
            'created_at' => TIMESTAMP,
        );
        pdo_insert('bontrip_auth_code', $data);

        return $this->__json(0);
    }

    //微信支付回调
    public function payResult($params)
    {
        //记录日志
        load()->func('logging');
        logging_run(array('payname' => '支付参数', 'type' => $params));

        //一些业务代码
        //根据参数params中的result来判断支付是否成功
        if ($params['result'] == 'success' && $params['from'] == 'notify') {
            //此处会处理一些支付成功的业务代码
            switch ($params['device_info']) {
                case "single":
                    //查找订单
                    $uniacid = intval($params['uniacid']);
                    $order = pdo_fetch("SELECT * FROM "
                        . tablename('bontrip_single_order') . " WHERE uniacid = '{$uniacid}' AND order_no = '{$params['tid']} ' AND deleted_at IS NULL");
                    if (!empty($order)) {
                        //匹配金额
                        if ($order['total_price'] == $params['fee']) {
                            //更新状态
                            $data = array(
                                'status' => 1,
                                'pay_no' => $params['tag']['transaction_id'],
                                'payment_time' => $params['paytime']
                            );
                            pdo_update('bontrip_single_order', $data, array('id' => $order['id']));
                        }
                    }
                    break;
                case "oneday":
                    //查找订单
                    $uniacid = intval($params['uniacid']);
                    $order = pdo_fetch("SELECT * FROM "
                        . tablename('bontrip_oneday_order') . " WHERE uniacid = '{$uniacid}' AND order_no = '{$params['tid']} ' AND deleted_at IS NULL");
                    if (!empty($order)) {
                        //匹配金额
                        if ($order['total_price'] == $params['fee']) {
                            //更新状态
                            $data = array(
                                'status' => 1,
                                'pay_no' => $params['tag']['transaction_id'],
                                'payment_time' => $params['paytime']
                            );
                            pdo_update('bontrip_oneday_order', $data, array('id' => $order['id']));
                        }
                    }
                    break;
                case "quality":
                    //查找订单
                    $uniacid = intval($params['uniacid']);
                    $order = pdo_fetch("SELECT * FROM "
                        . tablename('bontrip_quality_order') . " WHERE uniacid = '{$uniacid}' AND order_no = '{$params['tid']} ' AND deleted_at IS NULL");
                    if (!empty($order)) {
                        //匹配金额
                        if ($order['total_price'] == $params['fee']) {
                            //更新状态
                            $data = array(
                                'status' => 1,
                                'pay_no' => $params['tag']['transaction_id'],
                                'payment_time' => $params['paytime']
                            );
                            pdo_update('bontrip_quality_order', $data, array('id' => $order['id']));
                        }
                    }
                    break;
                case "insurance":
                    //查找订单
                    $uniacid = intval($params['uniacid']);
                    $insurance_order = pdo_fetch("SELECT * FROM "
                        . tablename('bontrip_insurance_order') . " WHERE uniacid = '{$uniacid}' AND order_no = '{$params['tid']} ' AND deleted_at IS NULL");
                    if (!empty($insurance_order)) {
                        //匹配金额
                        if ($insurance_order['total_price'] == $params['fee']) {
                            //更新状态
                            $data = array(
                                'status' => 1,
                                'pay_no' => $params['tag']['transaction_id'],
                                'payment_time' => $params['paytime']
                            );
                            pdo_update('bontrip_insurance_order', $data, array('id' => $insurance_order['id']));
                        }
                    }
                    break;
            }
        }
    }

    /*
    * 发送手机短信
    * @param unknown $mobile 手机号
    * @param unknown $content 短信内容
   */
    private function send($mobile, $content)
    {
        global $_W;
        //获取参数配置
        $setting = pdo_fetch("SELECT settings FROM " . tablename('uni_account_modules') . " WHERE module = :module AND uniacid = :uniacid", array(':module' => 'vj_bontrip', ':uniacid' => $_W['uniacid']));
        $setting = iunserializer($setting['settings']);
        if (!empty($setting) && !empty($setting["duanxinbao_uid"]) && !empty($setting["duanxinbao_pwd"])) {
            $user_id = $setting["duanxinbao_uid"]; // 这里填写用户名
            $pass = $setting["duanxinbao_pwd"];// 这里填登陆密码
            if (is_array($mobile)) $mobile = implode(",", $mobile);
            $mobile = urlencode($mobile);
            //$content=$content."【我的网站】";
            $c = urlencode($content);
            $pass = md5($pass);//MD5加密
            $url = "http://api.smsbao.com/sms?u=" . $user_id . "&p=" . $pass . "&m=" . $mobile . "&c=" . $c . "";
            $res = file_get_contents($url);
            $ok = ($res == "0");
            $data = array(
                'mobile' => $mobile,
                'content' => $content,
                'status' => $ok ? 1 : 0,
                'created_at' => TIMESTAMP
            );
            pdo_insert('bontrip_sms_log', $data);
            return $ok;
        } else {
            return false;
        }

    }

}